package com.gmlive.common.ui.widget;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gmlive.common.ui.R;
import com.gmlive.common.ui.util.ResHelper;

/**
 * 自定义的TitleBar控件：
 * 1、标题居中
 * 2、支持左右两边的图标设置
 * 3、右边的按钮支持设置文字
 *
 * @作者: 姜志敏
 * @日期: 2019-11-27
 */
public class IkTitleBar extends RelativeLayout {
    private ImageButton mNavButtonView;
    private ImageButton mCloseButtonView;
    private TextView mTitleTextView;
    private TextView mActionTextView;
    private ImageButton mActionButtonView;
    private FrameLayout mFlActionContainer;

    private Drawable mNavButtonDrawable;
    private int mTitleTextColor;

    private int mActionTextColor;

    private OnClickListener mActionListener;

    private OnClickListener mNavListener;

    private OnClickListener mExtraActionListener;

    public IkTitleBar(Context context) {
        this(context, null);
    }

    public IkTitleBar(Context context, AttributeSet attrs) {
        this(context, attrs, R.style.IkTitleBarStyle);
    }

    public IkTitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attributeSet) {
        inflate(context, R.layout.ik_title_bar, this);
        TypedArray a = context.obtainStyledAttributes(attributeSet, R.styleable.IkTitleBar);
        mTitleTextColor = a.getColor(R.styleable.IkTitleBar_ikTitleTextColor, 0xFF333333);
        mActionTextColor = a.getColor(R.styleable.IkTitleBar_ikActionTextColor, 0xFF333333);

        mNavButtonDrawable = a.getDrawable(R.styleable.IkTitleBar_ikTitleBarNavIcon);
        int dividerHeight = a.getDimensionPixelSize(R.styleable.IkTitleBar_ikTitleBarDividerHeight, 0);
        int dividerColor = a.getColor(R.styleable.IkTitleBar_ikTitleBarDividerColor, 0);
        int backgroundColor = a.getColor(R.styleable.IkTitleBar_ikTitleBarBackgroundColor, 0);
        String title = a.getString(R.styleable.IkTitleBar_ikTitle);
        a.recycle();

        Drawable backgroundDrawable = ResHelper.createItemSeparatorBg(dividerColor, backgroundColor, dividerHeight, false);
        setBackground(backgroundDrawable);

        mNavButtonView = findViewById(R.id.ik_title_bar_nav);
        mCloseButtonView = findViewById(R.id.ik_title_bar_close);
        mTitleTextView = findViewById(R.id.ik_title_bar_title);
        mActionButtonView = findViewById(R.id.ik_title_bar_icon_action);
        mActionTextView = findViewById(R.id.ik_title_bar_text_action);
        mFlActionContainer = findViewById(R.id.ik_title_bar_right_container);

        setTitle(title);
        mTitleTextView.setTextColor(mTitleTextColor);
        mActionTextView.setTextColor(mActionTextColor);

        setNavDrawable(mNavButtonDrawable);

        mNavButtonView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mNavListener != null) {
                    mNavListener.onClick(v);
                }
            }
        });

        mActionButtonView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mActionListener != null) {
                    mActionListener.onClick(v);
                }
            }
        });

        mActionTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mActionListener != null) {
                    mActionListener.onClick(v);
                }
            }
        });

        mCloseButtonView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mExtraActionListener != null) {
                    mExtraActionListener.onClick(v);
                }
            }
        });
    }

    public void setNavDrawable(int resId) {
        mNavButtonView.setImageResource(resId);
    }

    public void setNavDrawable(Drawable drawable) {
        mNavButtonView.setImageDrawable(drawable);
    }

    public void setNavListener(OnClickListener listener) {
        mNavListener = listener;
    }

    public void setTitle(int resId) {
        resetTitleLayoutParam();
        mTitleTextView.setText(resId);
    }

    public void setTitle(CharSequence title) {
        resetTitleLayoutParam();
        mTitleTextView.setText(title);
    }

    /**
     * 修改其他控件的可见性，必须调该方法
     */
    private void resetTitleLayoutParam() {
        //务必放在 post(runnable) 执行，否则会影响 margin 的测量
        mTitleTextView.post(new Runnable() {
            @Override
            public void run() {
                LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                //LayoutParams params = (LayoutParams) mTitleTextView.getLayoutParams();  //不要用这个，有时候设置的 margin 可能会不起作用
                int margin = getMaxMargin();
                params.setMargins(margin, 0, margin, 0);
                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                if (mTitleTextView != null) {
                    mTitleTextView.setLayoutParams(params);
                }
            }
        });
    }

    private int getMaxMargin() {
        if (mTitleTextView == null) return dpToPx(15);
        int spacing = dpToPx(10);
        int leftMargin, rightMargin;
        int[] location = new int[2];
        if (mCloseButtonView.getVisibility() == VISIBLE) {
            //注意，使用的是 getLocationInWindow，不要使用 getLocationOnScreen，否则会影响该控件在非屏幕宽度的弹窗里面的使用
            mCloseButtonView.getLocationInWindow(location);
            leftMargin = location[0] + mCloseButtonView.getWidth() + spacing;
        } else if (mNavButtonView.getVisibility() == VISIBLE) {
            mNavButtonView.getLocationInWindow(location);
            leftMargin = location[0] + mNavButtonView.getWidth() + spacing;
        } else {
            leftMargin = dpToPx(15);
        }
        if (hasExtraAction()) {
            mFlActionContainer.getLocationInWindow(location);
            rightMargin = getWindowWidth() - location[0] + spacing;
        } else {
            rightMargin = dpToPx(15);
        }
        //Log.d("IkTitle", "viewId = " + this + ", startMargin = " + leftMargin + ", endMargin = " + rightMargin);
        return Math.max(leftMargin, rightMargin);
    }

    /**
     * 右边是否有可见按钮
     */
    private boolean hasExtraAction() {
        return mActionButtonView.getVisibility() == VISIBLE || mActionTextView.getVisibility() == VISIBLE;
    }

    public void seTextAction(int resId, OnClickListener listener) {
        mActionTextView.setVisibility(VISIBLE);
        mActionButtonView.setVisibility(GONE);

        mActionTextView.setText(resId);
        mActionListener = listener;

        resetTitleLayoutParam();
    }

    public void setTextAction(CharSequence action, OnClickListener listener) {
        mActionTextView.setVisibility(VISIBLE);
        mActionButtonView.setVisibility(GONE);

        mActionTextView.setText(action);
        mActionListener = listener;

        resetTitleLayoutParam();
    }

    public void setIconAction(int resId, OnClickListener listener) {
        mActionTextView.setVisibility(GONE);
        mActionButtonView.setVisibility(VISIBLE);

        mActionButtonView.setImageResource(resId);
        mActionListener = listener;

        resetTitleLayoutParam();
    }

    public void setIconAction(Drawable drawable, OnClickListener listener) {
        mActionTextView.setVisibility(GONE);
        mActionButtonView.setVisibility(VISIBLE);

        mActionButtonView.setImageDrawable(drawable);
        mActionListener = listener;

        resetTitleLayoutParam();
    }

    public void setNavButtonEnable(boolean enable) {
        if (enable) {
            mNavButtonView.setVisibility(VISIBLE);
        } else {
            mNavButtonView.setVisibility(GONE);
        }

        resetTitleLayoutParam();
    }

    /**
     * 设置右边按钮是否可用，true时不处理
     */
    public void setRightButtonEnable(boolean enable) {
        if (!enable) {
            mActionTextView.setVisibility(GONE);
            mActionButtonView.setVisibility(GONE);
        }

        resetTitleLayoutParam();
    }

    public void setExtraNavButton(boolean visible, int resId, OnClickListener extraAction) {
        if (visible) {
            mExtraActionListener = extraAction;
            mCloseButtonView.setImageResource(resId);
            mCloseButtonView.setVisibility(VISIBLE);
        } else {
            mCloseButtonView.setVisibility(GONE);
            mExtraActionListener = null;
        }

        resetTitleLayoutParam();
    }

    public void setExtraNavButton(boolean visible, Drawable drawable, OnClickListener extraAction) {
        if (visible) {
            mExtraActionListener = extraAction;
            mCloseButtonView.setImageDrawable(drawable);
            mCloseButtonView.setVisibility(VISIBLE);
        } else {
            mCloseButtonView.setVisibility(GONE);
            mExtraActionListener = null;
        }

        resetTitleLayoutParam();
    }

    private int dpToPx(float dp) {
        return (int) (dp * (Resources.getSystem().getDisplayMetrics().densityDpi / 160f));
    }

    private int getWindowWidth() {
        Rect rect = new Rect();
        this.getWindowVisibleDisplayFrame(rect);
        return rect.right - rect.left;
    }
}
